package com.nowcoder.service;

import com.nowcoder.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

/**
 * @author by lvshh
 * @version 1.0
 * @date 2020/5/1 17:48
 */
@Service
public class LikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    //点赞
    public void like(int userId,int entityType,int enetityId,int entityUserId){


        redisTemplate.execute(new SessionCallback() {
            @Nullable
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,enetityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);

                boolean isMember = operations.opsForSet().isMember(entityLikeKey,userId);

                operations.multi();

                if (isMember){
                    //如果当前用户已经点赞，那么就移除userId，以取消点赞
                    operations.opsForSet().remove(entityLikeKey,userId);
                    //帖子或者回复的作者的赞减1
                    operations.opsForValue().decrement(userLikeKey);
                }else {
                    //如果未点赞
                    operations.opsForSet().add(entityLikeKey,userId);
                    //
                    operations.opsForValue().increment(userLikeKey);
                }
                return operations.exec();
            }
        });
    }

    //查询某实体点赞数量
    public long findEntityLikeCount(int entityType,int eneityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,eneityId);

        return redisTemplate.opsForSet().size(entityLikeKey);

    }

    //查询某人对某实体的点赞状态
    //1-点赞  0-未点赞
    public int findEntityLikeStatus(int userId,int entityType,int eneityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,eneityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey,userId) ? 1 : 0;

    }

    //查询某个用户获得的赞的数量
    public int findUserLikeCount(int userId){
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count.intValue();
    }
}
